package com.pray.praymall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.pray.common.to.es.SkuEsModel;
import com.pray.praymall.search.config.ElasticSearchConfig;
import com.pray.praymall.search.constant.EsConstant;
import com.pray.praymall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ProductSaveServiceImpl
 *
 * @author 魂悸魄
 * @date 2020/9/12 18:00
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    private RestHighLevelClient client;

    @Override
    public boolean productStatusUp(List<SkuEsModel> esModels) throws IOException {
        // 保存到es
        // 1、给es中建立索引
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel esModel : esModels) {
            // 1、构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(esModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(esModel);
            indexRequest.source(jsonString, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = client.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        // TODO 如果批量请求错误
        boolean hasFailures = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems())
                .map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("商品上架完成：{}", collect);
        return hasFailures;
    }
}
